package yxy.game.pm2.proto;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import yxy.apple.util.FileUtility;
import yxy.apple.util.JSONUtility;

public abstract class CommandGenerator {
	private boolean trusted = false;

	public CommandGenerator(boolean trusted) {
		this.trusted = trusted;
	}

	public boolean trusted() {
		return this.trusted;
	}

	public void generate(JSONArray json, File output, String encoding) throws IOException {
		FileUtility.create(output);
		String content = this.assemble(json);
		FileOutputStream fos = new FileOutputStream(output);
		fos.write(content.getBytes(encoding));
		fos.flush();
		fos.close();
	}

	protected String assemble(JSONArray json) {
		return this.assembleContainer(0, null, null, null, json);
	}

	protected String assembleContainer(int level, String type, String name, String comment, JSONArray fields) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(this.assembleHeader(level, type, name, comment));
		buffer.append(this.assembleFields(level + 1, type, fields));
		buffer.append(this.assembleFooter(level, type, name, comment));
		return buffer.toString();
	}

	protected String assembleFields(int level, String parent, JSONArray fields) {
		StringBuffer buffer = new StringBuffer();
		if (fields != null) {
			int size = fields.size();
			for (int i = 0; i < size; i++) {
				JSONObject field = JSONUtility.getJSONObject(fields, i, null);
				String value = JSONUtility.getString(field, "value", null);
				String comment = JSONUtility.getString(field, "comment", null);
				String name = JSONUtility.getString(field, "name", null);
				JSONArray descs = field.getJSONArray("desc");
				String desc = null;
				String messagefile = null;
				if (descs.size() > 0) {
					desc = descs.getString(0);
				}
				if (descs.size() > 1) {
					messagefile = descs.getString(1);
				}
				buffer.append(this.assembleField(level, parent, "int", name, comment, value, desc, messagefile));
			}
		}
		return buffer.toString();
	}

	protected String indent(int level) {
		StringBuffer buffer = new StringBuffer("");
		for (int i = 0; i < level; i++) {
			buffer.append("\t");
		}
		return buffer.toString();
	}

	protected abstract String assembleHeader(int level, String type, String name, String comment);

	protected abstract String assembleFooter(int level, String type, String name, String comment);

	protected abstract String assembleField(int level, String parent, String type, String name, String comment, String value, String desc, String messagefile);

}
